<?php

namespace app;

use libs\HttpRequest;

class ShortURL
{
    const shorturl_api_url = "http://apis.baidu.com/3023/shorturl/shorten";

    public static function query($url)
    {
        $res = HttpRequest::request(self::shorturl_api_url, ['url_long' => $url], ["apikey:aca5fdb7c77f2eba00027ff9114fd989"]);
        $date = self::formatDate($res);
        if ($date['errNum']) {
            $date = null;
        } else {
            $date = $date['urls'][0];
            $date['img'] = self::img($date['url_short']);
        }
        return $date;
    }

    public static function formatDate($date)
    {
        $ret = false;
        if ($date) {
            $ret = json_decode($date, true);
        }
        return $ret;
    }

    public static function img($url)
    {
        $pattern = "/&/";
        $url = preg_replace($pattern, "%26", $url);
        $url = "http://qr.liantu.com/api.php?text=" . $url;
        return $url;
    }

}